<template>
  <el-card class="department-list">
    <!-- 头部区域 -->
    <template #header>
      <page-header title="部门管理" />
    </template>

    <div class="content-wrapper">
      <!-- 左侧部门树 -->
      <div class="tree-wrapper">
        <div class="tree-header">
          <div class="search-bar">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索部门"
              clearable
              prefix-icon="search"
              @input="handleSearch"
              class="dept-search-input"
            >
              <template #append>
                <div class="status-select-wrapper">
                  <el-select 
                    v-model="filterStatus" 
                    placeholder="状态"
                    @change="handleFilterChange"
                  >
                    <el-option label="全部" :value="''" />
                    <el-option label="启用" :value="1" />
                    <el-option label="停用" :value="0" />
                  </el-select>
                </div>
              </template>
            </el-input>
          </div>
          
          <div class="tree-actions">
            <el-tooltip content="展开全部" placement="top">
              <el-button 
                link 
                :icon="ArrowDown"
                @click="expandAll"
              />
            </el-tooltip>
            <el-tooltip content="收起全部" placement="top">
              <el-button 
                link 
                :icon="ArrowUp"
                @click="collapseAll"
              />
            </el-tooltip>
            <el-tooltip content="刷新" placement="top">
              <el-button 
                link 
                :icon="Refresh"
                @click="refreshTree"
                :loading="loading"
              />
            </el-tooltip>
          </div>
        </div>

        <el-tree
          ref="treeRef"
          v-loading="loading"
          :data="filteredTreeData"
          :props="{ label: 'name' }"
          node-key="id"
          default-expand-all
          highlight-current
          draggable
          :allow-drop="handleAllowDrop"
          :allow-drag="handleAllowDrag"
          :expand-on-drag-enter="false"
          :filter-node-method="filterNode"
          @node-click="handleNodeClick"
          @node-drag-end="handleDragEnd"
        >
          <template #default="{ node, data }">
            <div class="custom-tree-node">
              <span class="node-content">
                <el-icon class="dept-icon">
                  <component :is="data.parent ? Folder : OfficeBuilding" />
                </el-icon>
                <span class="dept-name">{{ data.name }}</span>
                <el-tag 
                  size="small" 
                  :type="data.status === 1 ? 'success' : 'danger'"
                  class="dept-status"
                >
                  {{ data.status === 1 ? '启用' : '停用' }}
                </el-tag>
              </span>
              <div class="action-buttons" v-show="node.isCurrent">
                <el-button link type="primary" @click.stop="handleAdd(data)">
                  <el-icon><plus /></el-icon>
                  添加子部门
                </el-button>
                <el-button link type="primary" @click.stop="handleEdit(data)">
                  <el-icon><edit /></el-icon>
                  编辑
                </el-button>
                <el-button 
                  link 
                  type="danger" 
                  @click.stop="handleDelete(data)"
                  v-if="!data.children?.length && data.code !== 'ROOT'"
                >
                  <el-icon><delete /></el-icon>
                  删除
                </el-button>
              </div>
            </div>
          </template>
        </el-tree>
      </div>

      <!-- 右侧表单 -->
      <div class="form-wrapper" v-loading="formLoading">
        <el-form
          v-if="currentDepartment || isAdding"
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="上级部门" prop="parent_id">
            <el-input
              v-model="parentName"
              disabled
              placeholder="无"
            />
          </el-form-item>

          <el-form-item label="部门名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入部门名称"
            />
          </el-form-item>

          <!-- 隐藏部门编码表单项 -->
          <!-- <el-form-item label="部门编码" prop="code">
            <el-input
              v-model="formData.code"
              disabled
              :placeholder="isAdding ? '系统自动生成' : ''"
            />
          </el-form-item> -->

          <el-form-item label="英文名称" prop="name_en">
            <el-input
              v-model="formData.name_en"
              placeholder="请输入英文名称"
              id="dept-name-en"
              name="dept-name-en"
            />
          </el-form-item>

          <el-form-item label="显示排序" prop="order_num">
            <el-input-number
              v-model="formData.order_num"
              :min="0"
              :max="999"
              controls-position="right"
              id="dept-order-num"
              name="dept-order-num"
            />
          </el-form-item>

          <el-form-item label="负责人" prop="leader">
            <el-input
              v-model="formData.leader"
              placeholder="请输入负责人"
              id="dept-leader"
              name="dept-leader"
            />
          </el-form-item>

          <el-form-item label="联系电话" prop="phone">
            <el-input
              v-model="formData.phone"
              placeholder="请输入联系电话"
              id="dept-phone"
              name="dept-phone"
            />
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="formData.email"
              placeholder="请输入邮箱"
              id="dept-email"
              name="dept-email"
            />
          </el-form-item>

          <el-form-item label="部门状态" prop="status">
            <el-radio-group 
              v-model="formData.status"
              id="dept-status"
              name="dept-status"
            >
              <el-radio :value="1">启用</el-radio>
              <el-radio :value="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-divider>权限配置</el-divider>

          <el-form-item label="权限模板" prop="template_id">
            <el-select
              v-model="formData.template_id"
              placeholder="请选择权限模板"
              clearable
              id="dept-template"
              name="dept-template"
              @change="handleTemplateChange"
            >
              <el-option
                v-for="item in templates"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
                <div class="template-option">
                  <span class="name">{{ item.name }}</span>
                  <span class="description">{{ item.description || '暂无描述' }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="特殊规则" prop="rules">
            <permission-rule-editor
              v-model="formData.rules"
              :template-type="currentTemplateType"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </el-form-item>
        </el-form>
        <div v-else class="placeholder">
          <el-empty description="请选择部门" />
        </div>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowDown, 
  ArrowUp, 
  Refresh,
  Plus,
  Edit,
  Delete,
  OfficeBuilding,
  Folder,
  Search
} from '@element-plus/icons-vue'
import PageHeader from '@/components/PageHeader.vue'
import PermissionRuleEditor from '@/components/PermissionRuleEditor.vue'
import { departmentApi } from '@/api/departmentApi'
import { debounce } from 'lodash'

// 树形数据
const loading = ref(false)
const treeData = ref([])
const treeRef = ref(null)

// 表单数据
const formLoading = ref(false)
const formRef = ref(null)
const currentDepartment = ref(null)
const isAdding = ref(false)
const formData = ref({
  name: '',
  name_en: '',
  code: '',
  parent_id: null,
  leader: '',
  phone: '',
  email: '',
  status: 1,
  order_num: 0,
  template_id: '',
  rules: {
    system: [],
    business: [],
    data: {
      scope: 'self',
      fields: []
    }
  }
})

// 计算上级部门名称
const parentName = computed(() => {
  if (!formData.value.parent_id) return ''
  const parent = findDepartmentById(treeData.value, formData.value.parent_id)
  return parent ? parent.name : ''
})

// 表单验证规则
const rules = {
  name: [
    { 
      required: true,
      min: 2,
      max: 50,
      message: '部门名称必填且长度在 2 到 50 个字符',
      trigger: 'blur'
    }
  ],
  name_en: [
    { pattern: /^[A-Za-z0-9_\- ]+$/, message: '只能包含字母、数字、下划线、横线和空格', trigger: 'blur' },
    { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
  ],
  order_num: [
    { required: true, message: '请输入显示排序', trigger: 'blur' },
    { type: 'number', message: '显示排序必须为数字', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  template_id: [
    { required: true, message: '请选择权限模板', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择部门状态', trigger: 'change' },
    { type: 'number', message: '状态值不正确', trigger: 'change' }
  ]
}

// 加载部门树
const loadTree = async () => {
  loading.value = true
  try {
    const res = await departmentApi.getDepartmentTree()
    if (res.code === 200) {
      console.log('后端返回的原始数据:', res.data)
      
      const convertStatus = (nodes) => {
        return nodes.map(node => {
          // 如果状态未定义，使用表单中的状态值作为默认值
          const status = node.status === undefined 
            ? (currentDepartment.value?.id === node.id ? formData.value.status : 1)
            : Number(node.status)
          
          const convertedNode = {
            ...node,
            status,
            children: node.children ? convertStatus(node.children) : []
          }
          console.log(`部门 ${node.name} 的状态转换:`, {
            原始状态: node.status,
            转换后状态: status,
            是否未定义: node.status === undefined,
            是否当前部门: currentDepartment.value?.id === node.id,
            表单状态: formData.value.status
          })
          return convertedNode
        })
      }
      treeData.value = convertStatus(res.data)
      console.log('转换后的树形数据:', treeData.value)
    }
  } catch (error) {
    console.error('Load tree error:', error)
    ElMessage.error('加载部门树失败')
  } finally {
    loading.value = false
  }
}

// 递归查找部门
const findDepartmentById = (departments, id) => {
  for (const dept of departments) {
    if (dept.id === id) return dept
    if (dept.children?.length) {
      const found = findDepartmentById(dept.children, id)
      if (found) return found
    }
  }
  return null
}

// 点击节点
const handleNodeClick = async (data) => {
  try {
    // 确保模板已加载
    await loadTemplates()
    
    currentDepartment.value = data
    isAdding.value = false
    
    // 基本数据赋值
    Object.assign(formData.value, data)
    
    // 如果有模板，使用模板的权限配置
    if (data.template_id) {
      const template = templates.value.find(t => t.id === data.template_id)
      if (template) {
        handleTemplateChange(template.id)
      }
    } else {
      // 如果没有模板，解析部门自身的权限配置
      formData.value.rules = typeof data.rules === 'string' ? JSON.parse(data.rules) : (data.rules ?? {
        system: [],
        business: [],
        data: {
          scope: 'self',
          fields: []
        }
      })
    }
  } catch (error) {
    console.error('Handle node click error:', error)
    ElMessage.error('加载部门数据失败')
  }
}

// 添加部门
const handleAdd = async (node) => {
  try {
    isAdding.value = true
    currentDepartment.value = null
    
    await loadTemplates()
    
    const normalTemplate = templates.value.find(t => t.code === 'normal')
    const defaultTemplateId = normalTemplate ? Number(normalTemplate.id) : null
    
    formData.value = {
      name: '',
      name_en: '',
      code: '',
      parent_id: node ? node.id : null,
      leader: '',
      phone: '',
      email: '',
      status: 1,  // 默认启用
      template_id: defaultTemplateId,
      rules: {
        system: [],
        business: [],
        data: {
          scope: 'self',
          fields: []
        }
      },
      level: node ? node.level + 1 : 1,
      order_num: 0
    }

    if (defaultTemplateId) {
      handleTemplateChange(defaultTemplateId)
    }
  } catch (error) {
    console.error('Add department error:', error)
    ElMessage.error('初始化部门数据失败')
  }
}

// 编辑部门
const handleEdit = async (node) => {
  loading.value = true
  try {
    // 确保模板已加载
    await loadTemplates()

    if (!node.parent) {
      // 获取当前模板
      const template = templates.value.find(t => t.id === node.template_id)
      
      formData.value = {
        ...node,
        level: 1,
        parent_id: null,
        status: Number(node.status),  // 直接使用数字状态值
        template_id: node.template_id ?? null
      }
      
      // 如果有模板，使用模板的权限配置
      if (template) {
        handleTemplateChange(template.id)
      } else {
        formData.value.rules = typeof node.rules === 'string' ? JSON.parse(node.rules) : (node.rules ?? {})
      }
      
      currentDepartment.value = node
      isAdding.value = false
      return
    }

    const res = await departmentApi.getDepartment(node.id)
    if (res.code === 200) {
      const data = {
        ...res.data,
        status: Number(res.data.status),  // 直接使用数字状态值
        level: res.data.level || (node.parent ? node.parent.level + 1 : 1)
      }
      
      // 获取当前模板
      const template = templates.value.find(t => t.id === data.template_id)
      
      formData.value = data
      currentDepartment.value = res.data
      isAdding.value = false

      // 如果有模板，使用模板的权限配置
      if (template) {
        handleTemplateChange(template.id)
      } else {
        formData.value.rules = typeof res.data.rules === 'string' ? JSON.parse(res.data.rules) : (res.data.rules ?? {})
      }
    }
  } catch (error) {
    console.error('Load department error:', error)
    ElMessage.error('加载部门失败')
  } finally {
    loading.value = false
  }
}

// 删除部门
const handleDelete = async (data) => {
  try {
    await ElMessageBox.confirm('确认删除该部门吗？', '提示', {
      type: 'warning'
    })
    const res = await departmentApi.deleteDepartment(data.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      if (currentDepartment.value?.id === data.id) {
        currentDepartment.value = null
      }
      loadTree()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Delete department error:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单前的额外验证
const validateForm = async () => {
  try {
    await formRef.value.validate()
    
    // 验证权限规则格式
    if (formData.value.rules) {
      try {
        const rules = JSON.parse(formData.value.rules)
        if (!validateRules(rules)) {
          ElMessage.error('权限规则格式不正确')
          return false
        }
      } catch (error) {
        ElMessage.error('请输入有效的JSON格式')
        return false
      }
    }
    
    return true
  } catch (error) {
    return false
  }
}

// 修改提交处理函数
const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    
    console.log('表单提交前的状态值:', {
      表单状态: formData.value.status,
      当前部门: currentDepartment.value
    })

    const method = currentDepartment.value ? 'updateDepartment' : 'createDepartment'
    
    // 如果是新增部门且没有编码，先获取编码
    if (!currentDepartment.value && !formData.value.code) {
      try {
        const res = await departmentApi.generateCode(formData.value.parent_id)
        if (res.code === 200) {
          formData.value.code = res.data
        } else {
          ElMessage.error('获取部门编码失败')
          return
        }
      } catch (error) {
        console.error('Generate code error:', error)
        ElMessage.error('获取部门编码失败')
        return
      }
    }

    const { id, children, hasChildren, template, ...rest } = formData.value
    const submitData = {
      ...rest,
      name: formData.value.name.trim(),
      name_en: formData.value.name_en?.trim() || null,
      leader: formData.value.leader?.trim() || null,
      phone: formData.value.phone?.trim() || null,
      email: formData.value.email?.trim() || null,
      level: Number(formData.value.level),
      order_num: Number(formData.value.order_num || 0),
      template_id: formData.value.template_id || null,
      rules: formData.value.rules ? JSON.stringify(formData.value.rules) : null,
      code: formData.value.code?.trim(),
      status: Number(formData.value.status)  // 直接使用数字类型的状态值
    }
    
    console.log('准备提交到后端的数据:', submitData)
    
    const res = await (method === 'createDepartment' 
      ? departmentApi.createDepartment(submitData)
      : departmentApi.updateDepartment(currentDepartment.value.id, submitData)
    )
    
    if (res.code === 200) {
      console.log('后端返回的响应:', res)
      ElMessage.success(currentDepartment.value ? '更新成功' : '创建成功')
      loadTree()
      if (!currentDepartment.value) {
        handleCancel()
      }
    }
  } catch (error) {
    console.error('Save department error:', error)
    ElMessage.error(error.response?.data?.message || error.message || '保存失败')
  }
}

// 取消编辑
const handleCancel = () => {
  currentDepartment.value = null
  isAdding.value = false
  formRef.value?.resetFields()
}

// 拖拽结束
const handleDragEnd = async (draggingNode, dropNode, dropType) => {
  // 基础检查
  if (!dropNode || !draggingNode) {
    loadTree()
    return
  }

  try {
    // 直接设置为最后一个子节点
    const siblings = dropNode.childNodes || []
    const newOrderNum = siblings.length 
      ? Math.min(...siblings.map(node => node.data.order_num)) - 10
      : 0

    // 更新数据，总是作为子节点
    const updateData = {
      orders: [{
        id: draggingNode.data.id,
        parent_id: dropNode.data.id,
        order_num: Math.max(0, newOrderNum)
      }]
    }

    const res = await departmentApi.updateOrder(updateData)
    if (res.code === 200) {
      ElMessage.success('移动成功')
      loadTree()
    }
  } catch (error) {
    console.error('Update order error:', error)
    ElMessage.error(error.response?.data?.message || '移动失败')
    loadTree() // 重新加载以还原位置
  }
}

// 检查是否是子节点
const isChildNode = (parentNode, targetId) => {
  if (!parentNode.children) return false
  return parentNode.children.some(child => 
    child.id === targetId || isChildNode(child, targetId)
  )
}

// 权限模板列表
const templates = ref([])

// 加载权限模板
const loadTemplates = async () => {
  try {
    const res = await departmentApi.getTemplates()
    if (res.code === 200) {
      templates.value = res.data
    }
  } catch (error) {
    console.error('Load templates error:', error)
    ElMessage.error('加载权限模板失败')
  }
}

// 处理模板变更
const handleTemplateChange = (templateId) => {
  console.log('模板变更 - 开始:', {
    templateId,
    当前表单数据: formData.value
  })

  if (!templateId) {
    console.log('模板ID为空，重置权限')
    formData.value.rules = {
      system: [],
      business: [],
      data: {
        scope: 'self',
        fields: []
      }
    }
    return
  }
  
  const template = templates.value.find(t => t.id === templateId)
  if (!template) {
    console.log('未找到对应的模板:', templateId)
    return
  }

  console.log('找到模板:', {
    模板ID: template.id,
    模板代码: template.code,
    模板名称: template.name,
    原始权限: template.permissions
  })

  // 根据模板类型设置不同的默认权限
  let permissions
  switch (template.code) {
    case 'super_admin_template':  // 超级管理员模板 - 全选所有权限
      console.log('设置超级管理员权限')
      permissions = {
        system: [
          'view',
          'add',
          'edit',
          'delete'
        ],  // 所有系统权限
        business: [
          'view',
          'export',
          'import'
        ],  // 所有业务权限
        data: {
          scope: 'all',  // 所有数据
          fields: [
            'basic',
            'sensitive'
          ]  // 所有字段权限
        }
      }
      break
    case 'dept_admin_template':  // 部门管理员模板
      console.log('设置部门管理员权限')
      permissions = {
        system: [
          'view',
          'add',
          'edit',
          'delete'
        ],  // 所有系统权限
        business: [
          'view',
          'export',
          'import'
        ],  // 所有业务权限
        data: {
          scope: 'department',  // 本部门数据
          fields: [
            'basic',
            'sensitive'
          ]  // 所有字段权限
        }
      }
      break
    case 'normal_user_template':  // 普通用户模板
      console.log('设置普通用户权限')
      permissions = {
        system: ['view'],  // 只有查看权限
        business: ['view'],  // 只有查看权限
        data: {
          scope: 'self',  // 个人数据
          fields: ['basic']  // 基础字段
        }
      }
      break
    default:  // 自定义模板
      console.log('使用自定义模板权限')
      permissions = {
        ...template.permissions,
        system: template.permissions.system || [],
        business: template.permissions.business || [],
        data: {
          scope: template.permissions.data?.scope || 'self',
          fields: template.permissions.data?.fields || []
        }
      }
      break
  }
  
  console.log('最终设置的权限:', {
    模板类型: template.code,
    权限配置: permissions,
    系统权限数量: permissions.system.length,
    业务权限数量: permissions.business.length,
    字段权限数量: permissions.data.fields.length
  })

  formData.value.rules = permissions

  console.log('模板变更 - 完成:', {
    最终表单数据: formData.value
  })
}

// 计算是否禁用权限编辑
const isPermissionDisabled = computed(() => {
  if (!formData.value.template_id) return false
  const template = templates.value.find(t => t.id === formData.value.template_id)
  return template?.code === 'admin' || template?.code === 'normal'
})

// 判断是否允许拖拽
const handleAllowDrag = (node) => {
  // 根节点不允许拖动
  return node.data.code !== 'root'
}

// 判断是否允许放置
const handleAllowDrop = (draggingNode, dropNode, type) => {
  // 如果任一节点不存在，不允许放置
  if (!draggingNode?.data || !dropNode?.data) {
    return false
  }

  // 不能拖到自己
  if (draggingNode.data.id === dropNode.data.id) {
    return false
  }
  
  // 不能拖到自己的子节点下
  if (isChildNode(draggingNode.data, dropNode.data.id)) {
    return false
  }

  // 打印拖拽相关信息
  console.log('拖拽类型:', type)
  console.log('目标节点ID:', dropNode.data.id)
  console.log('目标节点名称:', dropNode.data.name)

  // 只允许放置到节点内部
  return type === 'inner'
}

// 计算当前模板类型
const currentTemplateType = computed(() => {
  if (!formData.value.template_id) return 'custom'
  const template = templates.value.find(t => t.id === formData.value.template_id)
  return template?.code || 'custom'
})

// 验证权限规则结构
const validateRules = (rules) => {
  // 验证系统权限
  if (rules.system && !Array.isArray(rules.system)) {
    return false
  }
  
  // 验证业务权限
  if (rules.business && !Array.isArray(rules.business)) {
    return false
  }
  
  // 验证数据权限
  if (rules.data) {
    if (typeof rules.data !== 'object') return false
    
    // 验证数据范围
    if (rules.data.scope && !['all', 'department', 'self'].includes(rules.data.scope)) {
      return false
    }
    
    // 验证字段权限
    if (rules.data.fields && !Array.isArray(rules.data.fields)) {
      return false
    }
  }
  
  return true
}

// 添加表单错误状态
const formErrors = reactive({
  parent_id: '',
  name: '',
  code: '',
  name_en: '',
  order_num: '',
  leader: '',
  phone: '',
  email: '',
  status: '',
  template_id: '',
  rules: ''
})

// 搜索和过滤
const searchKeyword = ref('')
const filterStatus = ref('')
const isFiltering = computed(() => searchKeyword.value || filterStatus.value !== '')

// 修改过滤后的树形数据计算属性，添加详细日志
const filteredTreeData = computed(() => {
  console.log('开始筛选，当前条件:', {
    是否在筛选: isFiltering.value,
    关键字: searchKeyword.value,
    状态值: filterStatus.value
  })
  console.log('原始树数据:', treeData.value)

  if (!isFiltering.value) {
    console.log('没有筛选条件，返回原始数据')
    return treeData.value
  }
  
  const filterTree = (nodes) => {
    if (!nodes) return nodes
    
    return nodes.map(node => {
      console.log(`\n处理节点 "${node.name}":`, {
        节点ID: node.id,
        原始状态: node.status,
        子节点数量: node.children?.length || 0
      })

      const newNode = { ...node }
      
      // 关键字过滤
      const matchesSearch = searchKeyword.value
        ? node.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
          node.name_en?.toLowerCase().includes(searchKeyword.value.toLowerCase())
        : true
      
      console.log(`关键字匹配结果:`, {
        节点: node.name,
        搜索词: searchKeyword.value,
        是否匹配: matchesSearch
      })

      // 状态过滤 - 严格使用数字比较
      const matchesStatus = filterStatus.value === '' || 
        Number(node.status) === Number(filterStatus.value)
      
      console.log(`状态匹配结果:`, {
        节点: node.name,
        节点状态: node.status,
        筛选状态: filterStatus.value,
        是否匹配: matchesStatus
      })
      
      // 递归处理子节点
      if (node.children?.length) {
        newNode.children = filterTree(node.children)
        console.log(`处理完子节点:`, {
          父节点: node.name,
          剩余子节点数: newNode.children?.length || 0
        })
      }

      // 返回节点的条件判断
      const shouldKeepNode = !isFiltering.value || 
        (matchesSearch && matchesStatus) || 
        newNode.children?.length

      console.log(`节点 "${node.name}" 的最终处理结果:`, {
        保留节点: shouldKeepNode,
        原因: shouldKeepNode 
          ? (!isFiltering.value 
              ? '无筛选条件' 
              : (matchesSearch && matchesStatus)
                ? '匹配筛选条件'
                : '有匹配的子节点')
          : '不匹配任何条件'
      })
      
      return shouldKeepNode ? newNode : null
    }).filter(Boolean)
  }
  
  const result = filterTree([...treeData.value])
  console.log('筛选后的最终结果:', result)
  return result
})

// 搜索处理
const handleSearch = debounce(() => {
  treeRef.value?.filter(searchKeyword.value)
}, 300)

// 状态过滤处理
const handleFilterChange = () => {
  treeRef.value?.filter(searchKeyword.value)
}

// 节点过滤方法
const filterNode = (value, data) => {
  if (!value) return true
  return data.name.toLowerCase().includes(value.toLowerCase()) ||
         data.name_en?.toLowerCase().includes(value.toLowerCase())
}

// 树操作方法
const expandAll = () => {
  const treeNodes = treeRef.value?.store.nodesMap
  if (treeNodes) {
    Object.values(treeNodes).forEach(node => {
      node.expand()
    })
  }
}

const collapseAll = () => {
  const treeNodes = treeRef.value?.store.nodesMap
  if (treeNodes) {
    Object.values(treeNodes).forEach(node => {
      if (node.level !== 0) {
        node.collapse()
      }
    })
  }
}

const refreshTree = async () => {
  if (loading.value) return
  await loadTree()
  ElMessage.success('刷新成功')
}

// 初始化
onMounted(() => {
  loadTree()
  loadTemplates()
})
</script>

<style lang="scss" scoped>
.department-list {
  height: 100%;
  margin: -20px;
  
  :deep(.el-card__body) {
    height: calc(100% - 61px);
    padding: 20px;
  }
}

.content-wrapper {
  display: flex;
  gap: 20px;
  height: 100%;
}

.tree-wrapper {
  width: 45%;
  border-right: 1px solid var(--el-border-color-light);
  padding-right: 20px;
  overflow: auto;
  
  .tree-header {
    margin-bottom: 16px;
    
    .search-bar {
      margin-bottom: 8px;
      
      :deep(.el-input-group__append) {
        padding: 0;
        background-color: var(--el-fill-color-light);
      }
    }
    
    .tree-actions {
      display: flex;
      justify-content: flex-end;
      gap: 8px;
      padding: 4px 0;
      border-bottom: 1px solid var(--el-border-color-light);
      
      .el-button {
        padding: 4px;
        
        &:hover {
          color: var(--el-color-primary);
        }
      }
    }
  }
  
  :deep(.el-tree-node__content) {
    height: auto;
    padding: 4px 0;
  }
  
  :deep(.el-tree-node.is-current > .el-tree-node__content) {
    background-color: var(--el-color-primary-light-9);
  }
}

.form-wrapper {
  width: 45%;
  overflow: auto;
  
  .placeholder {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  :deep(.el-form-item) {
    margin-bottom: 18px;
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
  
  &:hover {
    background-color: var(--el-fill-color-light);
  }
  
  .node-content {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .dept-icon {
      color: var(--el-text-color-secondary);
    }
    
    .dept-name {
      font-weight: 500;
    }
    
    .dept-status {
      margin-left: 8px;
    }
  }
  
  .action-buttons {
    opacity: 0;
    transition: opacity 0.2s;
    display: flex;
    gap: 8px;
    
    .el-button {
      padding: 4px 8px;
      
      .el-icon {
        margin-right: 4px;
      }
    }
  }
  
  &:hover .action-buttons {
    opacity: 1;
  }
}

.template-option {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 4px 0;
  
  .name {
    font-weight: 500;
  }
  
  .description {
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }
}

.dept-search-input {
  :deep(.el-input-group__append) {
    padding: 0;
    background-color: var(--el-fill-color-light);
  }
}

.status-select-wrapper {
  width: 120px;
  height: 100%;
  background-color: var(--el-fill-color-light);
  display: flex;
  align-items: center;
  justify-content: center;

  :deep(.el-select) {
    width: 100%;

    .el-input__wrapper {
      box-shadow: none;
      background: transparent;
      padding: 0 8px;
    }

    .el-input__inner {
      text-align: center;
    }
  }
}
</style> 